// 网络请求工具
const BASE_URL = 'https://api.example.com' // 替换为你的API地址

// 请求拦截器
const requestInterceptor = (config) => {
  // 添加token
  const token = uni.getStorageSync('token')
  if (token) {
    config.header = {
      ...config.header,
      'Authorization': `Bearer ${token}`
    }
  }
  
  // 添加基础URL
  if (!config.url.startsWith('http')) {
    config.url = BASE_URL + config.url
  }
  
  return config
}

// 响应拦截器
const responseInterceptor = (response) => {
  const { statusCode, data } = response
  
  if (statusCode === 200) {
    // 根据后端返回的数据结构判断
    if (data.code === 0 || data.code === 200) {
      return data.data || data
    } else {
      // 业务错误
      uni.showToast({
        title: data.message || '请求失败',
        icon: 'none'
      })
      return Promise.reject(data)
    }
  } else if (statusCode === 401) {
    // token过期，跳转登录
    uni.removeStorageSync('token')
    uni.showToast({
      title: '登录已过期，请重新登录',
      icon: 'none'
    })
    // 跳转到登录页
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/login/login'
      })
    }, 1500)
    return Promise.reject(response)
  } else {
    // 网络错误
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
    return Promise.reject(response)
  }
}

// 封装请求方法
export const request = (options) => {
  return new Promise((resolve, reject) => {
    const config = requestInterceptor(options)
    
    uni.request({
      ...config,
      success: (res) => {
        try {
          const result = responseInterceptor(res)
          resolve(result)
        } catch (error) {
          reject(error)
        }
      },
      fail: (error) => {
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        })
        reject(error)
      }
    })
  })
}

// 常用请求方法
export const get = (url, params = {}, options = {}) => {
  const query = Object.keys(params).map(key => `${key}=${params[key]}`).join('&')
  const fullUrl = query ? `${url}?${query}` : url
  
  return request({
    url: fullUrl,
    method: 'GET',
    ...options
  })
}

export const post = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    header: {
      'Content-Type': 'application/json',
      ...options.header
    },
    ...options
  })
}

export const put = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    header: {
      'Content-Type': 'application/json',
      ...options.header
    },
    ...options
  })
}

export const del = (url, options = {}) => {
  return request({
    url,
    method: 'DELETE',
    ...options
  })
}

// 上传文件
export const upload = (url, filePath, options = {}) => {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')
    const header = token ? { 'Authorization': `Bearer ${token}` } : {}
    
    uni.uploadFile({
      url: BASE_URL + url,
      filePath,
      name: 'file',
      header,
      ...options,
      success: (res) => {
        try {
          const data = JSON.parse(res.data)
          if (data.code === 0 || data.code === 200) {
            resolve(data.data || data)
          } else {
            uni.showToast({
              title: data.message || '上传失败',
              icon: 'none'
            })
            reject(data)
          }
        } catch (error) {
          reject(error)
        }
      },
      fail: (error) => {
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        })
        reject(error)
      }
    })
  })
} 